#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, Integer, Unicode, DateTime, \
    func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""AnalyzeDown collection has
    rip:        远程ip（string）
    platform:   平台(string)
    source:     来源（string）
    ctime:      访问时间(datetime)
"""


class AnalyzeDownItem(object):

    def to_dict(self):
        res = {}
        res['rip'] = self.rip
        res['platform'] = self.platform
        res['source'] = self.source
        res['ctime'] = self.ctime.strftime('%Y-%m-%d %H:%M:%S')\
            if self.ctime else ''
        return res

    def __repr__(self):
        return "%d" % self.source


analyze_down_table = Table(
    'analyze_down', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('rip', Unicode(65), nullable=False),
    Column('platform', Unicode(191), nullable=False),
    Column('source', Unicode(65), nullable=False),
    Column('ctime', DateTime, default=datetime.now, nullable=False),
)

mapper(AnalyzeDownItem, analyze_down_table)


def create_analyze_down_table_if_not_exist():
    metadata.create_all(engine)


def add_analyze_down_item(p_item):
    item = AnalyzeDownItem()
    item.rip = p_item['rip']
    item.platform = p_item['platform']
    item.source = p_item['source']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


if __name__ == "__main__":
    create_analyze_down_table_if_not_exist()